<template>
  <div class="page-box" style="position: relative;">
    <el-form
      ref="formCustomerInfoRef"
      :size="layoutStore.defaultFormItemSize"
      label-width="120px"
      label-position="right"
      @submit.prevent
    >
      <filter-box :item-width="350" @search="refreshFormCustomerInfo()" @reset="resetFormCustomerInfo">
        <el-form-item label="姓">
          <el-input
            class="filter-item"
            v-model="formFilter.lastNameFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="名">
          <el-input
            class="filter-item"
            v-model="formFilter.firstNameFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="电子邮件">
          <el-input
            class="filter-item"
            v-model="formFilter.emailFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="电话号码">
          <el-input
            class="filter-item"
            v-model="formFilter.phoneNumberFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="性别">
          <el-select
            class="filter-item"
            v-model="formFilter.genderFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="genderFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in genderFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码">
          <el-input
            class="filter-item"
            v-model="formFilter.idNumberFilter"
            type="text"
            placeholder=""
            :clearable="true"
            :show-word-limit="false"
            maxlength=""
          />
        </el-form-item>
        <el-form-item label="省">
          <el-select
            class="filter-item"
            v-model="formFilter.provinceCodeFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="provinceCodeFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in provinceCodeFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="市">
          <el-select
            class="filter-item"
            v-model="formFilter.cityCodeFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="cityCodeFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in cityCodeFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="区">
          <el-select
            class="filter-item"
            v-model="formFilter.districtCodeFilter"
            placeholder=""
            :clearable="true"
            :filterable="true"
            @visible-change="districtCodeFilterWidget.onVisibleChange"
          >
            <el-option
              v-for="item in districtCodeFilterWidgetDropdownList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </filter-box>
    </el-form>
    <table-box
      ref="formCustomerInfoTable"
      class="page-table"
      :data="formCustomerInfoTableWidgetDataList"
      :size="layoutStore.defaultFormItemSize"
      :row-config="{isCurrent: false, isHover: true}"
      :seq-config="{startIndex: ((formCustomerInfoTableWidgetCurrentPage - 1) * formCustomerInfoTableWidgetPageSize)}"
      :sort-config="{remote: true}"
      :hasExtend="true"
      @sort-change="formCustomerInfoTableWidget.onSortChange"
      @refresh="formCustomerInfoTableWidget.refreshTable()"
    >
      <template #operator>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formCustomerInfo:formCustomerInfo:addCustomerInfo')"
          @click="onAddCustomerInfoClick()"
          >
          新建
        </el-button>
        <el-button
          type="primary"
          :size="layoutStore.defaultFormItemSize"
          :disabled="!checkPermCodeExist('formCustomerInfo:formCustomerInfo:exportCustomerInfo')"
          @click="onExportCustomerInfoClick()"
          >
          导出
        </el-button>
        <el-upload
          class="btn-import"
          :auto-upload="false"
          action=""
          :show-file-list="false"
          accept=".xls,.xlsx"
          style="display: inline-block;"
          :disabled="!checkPermCodeExist('formCustomerInfo:formCustomerInfo:importCustomerInfo')"
          :on-change="onImportCustomerInfoClick"
        >
          <template #trigger>
            <el-button
              type="primary"
              :size="layoutStore.defaultFormItemSize"
              :disabled="!checkPermCodeExist('formCustomerInfo:formCustomerInfo:importCustomerInfo')"
            >
              导入
            </el-button>
          </template>
        </el-upload>
      </template>
      <vxe-column title="序号" type="seq" :index="formCustomerInfoTableWidget.getTableIndex" :width="80" />
      <vxe-column title="名" field="firstName" />
      <vxe-column title="姓" field="lastName" />
      <vxe-column title="电子邮件" field="email" />
      <vxe-column title="电话号码" field="phoneNumber" />
      <vxe-column title="性别" field="genderDictMap.name" />
      <vxe-column title="出生日期" field="birthDate">
        <template v-slot="scope">
          <span>{{formatDateByStatsType(scope.row.birthDate, 'day')}}</span>
        </template>
      </vxe-column>
      <vxe-column title="证件类型" field="idTypeDictMap.name" />
      <vxe-column title="证件号码" field="idNumber" />
      <vxe-column title="国籍" field="nationalityDictMap.name" />
      <vxe-column title="省" field="provinceCodeDictMap.name" />
      <vxe-column title="市" field="cityCodeDictMap.name" />
      <vxe-column title="区" field="districtCodeDictMap.name" />
      <vxe-column title="职业" field="occupation" />
      <vxe-column title="公司名称" field="companyName" />
      <vxe-column title="收入范围" field="incomeRangeDictMap.name" />
      <vxe-column title="紧急联系人姓名" field="emergencyContactName" />
      <vxe-column title="紧急联系人电话" field="emergencyContactPhone" />
      <vxe-column title="操作" fixed="right">
        <template v-slot="scope">
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onListCustomerAccountClick(scope.row)"
            :disabled="!checkPermCodeExist('formCustomerInfo:formCustomerInfo:listCustomerAccount')"
          >
            客户银行卡
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onEditCustomerInfoClick(scope.row)"
            :disabled="!checkPermCodeExist('formCustomerInfo:formCustomerInfo:editCustomerInfo')"
          >
            编辑
          </el-button>
          <el-button
            link
            type="primary"
            :size="layoutStore.defaultFormItemSize"
            @click.stop="onDeleteCustomerInfoClick(scope.row)"
            :disabled="!checkPermCodeExist('formCustomerInfo:formCustomerInfo:deleteCustomerInfo')"
          >
            删除
          </el-button>
        </template>
      </vxe-column>
      <template slot="empty">
        <div class="table-empty unified-font">
          <img src="@/assets/img/empty.png">
          <span>暂无数据</span>
        </div>
      </template>
      <!-- 分页 -->
      <template #pagination>
        <el-row type="flex" justify="end" style="margin-top: 10px;">
          <el-pagination
            :total="formCustomerInfoTableWidgetTotalCount"
            :current-page="formCustomerInfoTableWidgetCurrentPage"
            :page-size="formCustomerInfoTableWidgetPageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, prev, pager, next, sizes"
            @current-change="formCustomerInfoTableWidget.onCurrentPageChange"
            @size-change="formCustomerInfoTableWidget.onPageSizeChange">
          </el-pagination>
        </el-row>
      </template>
    </table-box>
    <label v-if="subPage" class="page-close-box" @click="onCancel()">
      <img src="@/assets/img/back2.png" alt="">
    </label>
  </div>
</template>

<script lang="ts">
export default {
  name: 'formCustomerInfo',
};
</script>

<script setup lang="ts">
import { VxeColumn, VxeTable } from 'vxe-table';
import { ANY_OBJECT } from '@/types/generic';
import { DictData, DictionaryBase } from '@/common/staticDict/types';
import { ElMessage, ElMessageBox, UploadFile } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import { useCommon } from '@/common/hooks/useCommon';
import { useLayoutStore, useStaticDictStore } from '@/store';
import { useDownload } from '@/common/hooks/useDownload';
import { useDropdown } from '@/common/hooks/useDropdown';
import { DropdownOptions, ListData } from '@/common/types/list';
import { useTable } from '@/common/hooks/useTable';
import { TableOptions } from '@/common/types/pagination';
import { useUpload } from '@/common/hooks/useUpload';
import { useUploadWidget } from '@/common/hooks/useUploadWidget';
import { DictionaryController } from '@/api/system';
import { treeDataTranslate, findItemFromList, findTreeNodePath, findTreeNode, stringCase } from '@/common/utils';
import { CustomerAccountData } from '@/api/generated/customerAccountController';
import { CustomerInfoData } from '@/api/generated/customerInfoController';
import { CustomerAccountController, CustomerInfoController } from '@/api/generated';
import FormCustomerAccount from '@/pages/Cust/formCustomerAccount.vue';
import FormEditCustomerInfo from '@/pages/Cust/formEditCustomerInfo.vue';

const router = useRouter();
const route = useRoute();
const layoutStore = useLayoutStore();
const { downloadFile } = useDownload();
const { getUploadHeaders, getUploadActionUrl, fileListToJson, parseUploadData, getPictureList } = useUpload();
const { 
  Delete,
  Search,
  Edit,
  Plus,
  Refresh,
  Picture,
  Dialog,
  mainContextHeight,
  clientHeight,
  checkPermCodeExist,
  parseParams,
  parseArrayParams,
  formatDateByStatsType,
  getDateRangeFilter,
} = useCommon();
// 静态字典
const { staticDict: StaticDict } = useStaticDictStore();

const props = withDefaults(
  defineProps<{
    subPage?: number | string | boolean;
  }>(),
  {
    subPage: 0,
  },
);

const formFilter = reactive({
  // 姓
  lastNameFilter: undefined,
  // 名
  firstNameFilter: undefined,
  // 电子邮件
  emailFilter: undefined,
  // 电话号码
  phoneNumberFilter: undefined,
  // 性别
  genderFilter: undefined,
  // 证件号码
  idNumberFilter: undefined,
  // 省
  provinceCodeFilter: undefined,
  // 市
  cityCodeFilter: undefined,
  // 区
  districtCodeFilter: undefined,
});
const formFilterCopy = reactive({
  // 姓
  lastNameFilter: undefined,
  // 名
  firstNameFilter: undefined,
  // 电子邮件
  emailFilter: undefined,
  // 电话号码
  phoneNumberFilter: undefined,
  // 性别
  genderFilter: undefined,
  // 证件号码
  idNumberFilter: undefined,
  // 省
  provinceCodeFilter: undefined,
  // 市
  cityCodeFilter: undefined,
  // 区
  districtCodeFilter: undefined,
});

const onCancel = () => {
  router.go(-1);
  layoutStore.removeCachePage(route.fullPath as string);
  route.meta.refreshParentCachedPage = true;
};

const onResume = () => {
  refreshFormCustomerInfo();
};

/**
 * 表格组件数据获取函数，返回Promise
 */
const loadFormCustomerInfoTableWidgetData = (params: ANY_OBJECT) => {
  if (params == null) params = {};
  params = {
    ...params,
    customerInfoDtoFilter: {
      firstName: formFilter.firstNameFilter,
      lastName: formFilter.lastNameFilter,
      email: formFilter.emailFilter,
      phoneNumber: formFilter.phoneNumberFilter,
      gender: formFilter.genderFilter,
      idNumber: formFilter.idNumberFilter,
      provinceCode: formFilter.provinceCodeFilter,
      cityCode: formFilter.cityCodeFilter,
      districtCode: formFilter.districtCodeFilter,
    }
  };
  return new Promise((resolve, reject) => {
    CustomerInfoController.list(params).then(res => {
      resolve({
        dataList: res.data.dataList,
        totalCount: res.data.totalCount
      });
    }).catch(e => {
      reject(e);
    });
  });
};
/**
 * 表格组件数据获取检测函数，返回true正常获取数据，返回false停止获取数据
 */
const loadFormCustomerInfoTableVerify = () => {
  formFilterCopy.lastNameFilter = formFilter.lastNameFilter;
  formFilterCopy.firstNameFilter = formFilter.firstNameFilter;
  formFilterCopy.emailFilter = formFilter.emailFilter;
  formFilterCopy.phoneNumberFilter = formFilter.phoneNumberFilter;
  formFilterCopy.genderFilter = formFilter.genderFilter;
  formFilterCopy.idNumberFilter = formFilter.idNumberFilter;
  formFilterCopy.provinceCodeFilter = formFilter.provinceCodeFilter;
  formFilterCopy.cityCodeFilter = formFilter.cityCodeFilter;
  formFilterCopy.districtCodeFilter = formFilter.districtCodeFilter;
  return true;
};
/**
 * 新建
 */
const onAddCustomerInfoClick = (row?: CustomerInfoData) => {
  let params: ANY_OBJECT = {
  };

  Dialog
    .show('新建', FormEditCustomerInfo, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formCustomerInfoTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 客户银行卡
 */
const onListCustomerAccountClick = (row?: CustomerInfoData) => {
  let params: ANY_OBJECT = {
    customerId: row?.customerId,
  };

  router.push({
    name: 'formCustomerAccount',
    query: { ...params, subPage: true }
  });
};
/**
 * 编辑
 */
const onEditCustomerInfoClick = (row?: CustomerInfoData) => {
  let params: ANY_OBJECT = {
    customerId: row?.customerId,
  };

  Dialog
    .show('编辑', FormEditCustomerInfo, { area: '900px' }, { ...params, subPage: true })
    .then(res => {
      formCustomerInfoTableWidget.refreshTable();
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
};
/**
 * 导出
 */
const onExportCustomerInfoClick = (row?: CustomerInfoData) => {
  let params: ANY_OBJECT = {
  };

  CustomerInfoController.export(params, '表格组件.xlsx').then(res => {
    ElMessage.success('导出成功');
  }).catch(e => {
    ElMessage.error(e.errorMessage);
  });
};
/**
 * 导入
 */
const onImportCustomerInfoClick = (file) => {
  let params: ANY_OBJECT = {
    importFile: file.raw,
    // 是否忽略表头
    skipHeader: false
  };

  CustomerInfoController.import(params).then(res => {
    ElMessage.success('导入成功');
    formCustomerInfoTableWidget.refreshTable();
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
/**
 * 删除
 */
const onDeleteCustomerInfoClick = (row?: CustomerInfoData) => {
  let params: ANY_OBJECT = {
    customerId: row?.customerId,
  };

  ElMessageBox.confirm('是否删除此记录？').then(res => {
    CustomerInfoController.delete(params).then(res => {
      ElMessage.success('删除成功');
      formCustomerInfoTableWidget.refreshTable(false, 1);
    }).catch(e => {
      // TODO: 异常处理
      console.error(e);
    });
  }).catch(e => {
    // TODO: 异常处理
    console.error(e);
  });
};
// 表格组件表格组件参数
const formCustomerInfoTableOptions: TableOptions<CustomerInfoData> = {
  loadTableData: loadFormCustomerInfoTableWidgetData,
  verifyTableParameter: loadFormCustomerInfoTableVerify,
  paged: true,
  rowSelection: false,
  orderFieldName: undefined,
  ascending: true,
};
// 表格组件表格组件
const formCustomerInfoTable = ref();
const formCustomerInfoTableWidget = useTable(formCustomerInfoTableOptions);
const {
  dataList: formCustomerInfoTableWidgetDataList,
  currentPage: formCustomerInfoTableWidgetCurrentPage,
  pageSize: formCustomerInfoTableWidgetPageSize,
  totalCount: formCustomerInfoTableWidgetTotalCount,
} = formCustomerInfoTableWidget;
/**
 * 性别下拉数据获取函数
 */
const loadGenderFilterDropdownList = (): Promise<ListData<DictData>> => {
  return Promise.resolve({
    dataList: StaticDict.Gender.getList(),
  });
};
// 性别配置参数
const genderFilterOptions: DropdownOptions<DictData> = {
  loadData: loadGenderFilterDropdownList,
  isTree: false,
};
// 性别下拉组件
const genderFilterWidget = useDropdown(genderFilterOptions);
const { dropdownList: genderFilterWidgetDropdownList } = genderFilterWidget
/**
 * 省下拉数据获取函数
 */
const loadProvinceCodeFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
    };
    DictionaryController.dictAreaCodeByParentId(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 省配置参数
const provinceCodeFilterOptions: DropdownOptions<DictData> = {
  loadData: loadProvinceCodeFilterDropdownList,
  isTree: false,
};
// 省下拉组件
const provinceCodeFilterWidget = useDropdown(provinceCodeFilterOptions);
const { dropdownList: provinceCodeFilterWidgetDropdownList } = provinceCodeFilterWidget
/**
 * 市下拉数据获取函数
 */
const loadCityCodeFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
      parentId: formFilter.provinceCodeFilter,
    };
    // 判断上级组件是否为空
    if (params.parentId == null || params.parentId === '') {
      resolve([]);
      return;
    }
    DictionaryController.dictAreaCodeByParentId(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 市配置参数
const cityCodeFilterOptions: DropdownOptions<DictData> = {
  loadData: loadCityCodeFilterDropdownList,
  isTree: false,
};
// 市下拉组件
const cityCodeFilterWidget = useDropdown(cityCodeFilterOptions);
const { dropdownList: cityCodeFilterWidgetDropdownList } = cityCodeFilterWidget
/**
 * 区下拉数据获取函数
 */
const loadDistrictCodeFilterDropdownList = (): Promise<ListData<DictData>> => {
  return new Promise((resolve, reject) => {
    const params = {
      parentId: formFilter.cityCodeFilter,
    };
    // 判断上级组件是否为空
    if (params.parentId == null || params.parentId === '') {
      resolve([]);
      return;
    }
    DictionaryController.dictAreaCodeByParentId(params).then(res => {
      resolve({
        dataList: res.getList(),
      });
    }).catch(e => {
      reject(e);
    });
  });
};
// 区配置参数
const districtCodeFilterOptions: DropdownOptions<DictData> = {
  loadData: loadDistrictCodeFilterDropdownList,
  isTree: false,
};
// 区下拉组件
const districtCodeFilterWidget = useDropdown(districtCodeFilterOptions);
const { dropdownList: districtCodeFilterWidgetDropdownList } = districtCodeFilterWidget
const refreshFormCustomerInfo = () => {
  // 刷新段落
  formCustomerInfoTableWidget.refreshTable();
};
/**
 * 重置过滤值
 */
const resetFormCustomerInfo = () => {
  formFilter.lastNameFilter = undefined;
  formFilterCopy.lastNameFilter = undefined;
  formFilter.firstNameFilter = undefined;
  formFilterCopy.firstNameFilter = undefined;
  formFilter.emailFilter = undefined;
  formFilterCopy.emailFilter = undefined;
  formFilter.phoneNumberFilter = undefined;
  formFilterCopy.phoneNumberFilter = undefined;
  formFilter.genderFilter = undefined;
  formFilterCopy.genderFilter = undefined;
  formFilter.idNumberFilter = undefined;
  formFilterCopy.idNumberFilter = undefined;
  formFilter.provinceCodeFilter = undefined;
  formFilterCopy.provinceCodeFilter = undefined;
  formFilter.cityCodeFilter = undefined;
  formFilterCopy.cityCodeFilter = undefined;
  formFilter.districtCodeFilter = undefined;
  formFilterCopy.districtCodeFilter = undefined;
  refreshFormCustomerInfo();
};
/**
 * 重置所有过滤值
 */
const resetFilter = () => {
  resetFormCustomerInfo();
};
const formInit = () => {
  genderFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  provinceCodeFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  cityCodeFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  watch(
    () => formFilter.provinceCodeFilter,
    () => {
      formFilter.cityCodeFilter = undefined;
      cityCodeFilterWidget.dirty.value = true;
    }
  );
  districtCodeFilterWidget.onVisibleChange(true).catch(e => {console.error(e)});
  watch(
    () => formFilter.cityCodeFilter,
    () => {
      formFilter.districtCodeFilter = undefined;
      districtCodeFilterWidget.dirty.value = true;
    }
  );
  refreshFormCustomerInfo();
};

onMounted(() => {
  formInit();
});

onActivated(() => {
  onResume();
});
</script>